package cn.msqweb.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.msqweb.constant.BusinessEnum;
import cn.msqweb.entity.MemberCollection;
import cn.msqweb.entity.Prod;
import cn.msqweb.feign.MemberProductFeign;
import cn.msqweb.mapper.MemberCollectionMapper;
import cn.msqweb.model.Result;
import cn.msqweb.service.MemberCollectionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MemberCollectionServiceImpl extends ServiceImpl<MemberCollectionMapper, MemberCollection> implements MemberCollectionService {

    @Resource
    private MemberCollectionMapper memberCollectionMapper;
    @Resource
    private MemberProductFeign memberProductFeign;
    @Override
    public Page<Prod> queryMemberCollectionProdPageByOpenId(String loginMemberOpenId, Long current, Long size) {
        Page<Prod> prodPage = new Page<>(current,size);
        Page<MemberCollection> collectionPage = new Page<>(current,size);
        collectionPage = memberCollectionMapper.selectPage(collectionPage,new LambdaQueryWrapper<MemberCollection>()
                .eq(MemberCollection::getOpenId,loginMemberOpenId)
                .orderByDesc(MemberCollection::getCreateTime)
        );
        // 从分页对象中获取收藏关系记录
        List<MemberCollection> memberCollectionList = collectionPage.getRecords();
        if (CollectionUtil.isNotEmpty(memberCollectionList) && memberCollectionList.size() != 0) {
            // 从收藏关系集合中获取商品id集合
            List<Long> prodIdList = memberCollectionList.stream().map(MemberCollection::getProdId).collect(Collectors.toList());
            // 远程调用：根据商品id集合查询商品对象集合
            Result<List<Prod>> listResult = memberProductFeign.getProdListByIds(prodIdList);
            if (listResult.getCode().equals(BusinessEnum.OPERATION_FAIL.getCode())) {
                throw new RuntimeException("远程调用：根据商品id集合查询商品对象集合 失败");
            }
            List<Prod> prodList = listResult.getData();
            prodPage.setRecords(prodList);
            prodPage.setTotal(collectionPage.getTotal());
            prodPage.setPages(collectionPage.getPages());
        }

        return prodPage;
    }
}
